package cloud.maque.auth.github;

import cloud.maque.auth.annotations.LoginTypeAnn;
import cloud.maque.auth.conf.AuthProperties;
import cloud.maque.auth.entity.AuthUser;
import cloud.maque.auth.model.LoginRequest;
import cloud.maque.auth.model.LoginResponse;
import cloud.maque.auth.model.Oauth2User;
import cloud.maque.auth.service.AuthService;
import cloud.maque.auth.service.CommUserService;
import cloud.maque.auth.service.UserThridService;
import cloud.maque.common.core.enums.LoginType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@LoginTypeAnn(LoginType.GITHUB)
public class GithubAuthServiceImpl implements AuthService {

    @Autowired
    UserThridService thridService;

    @Autowired
    AuthProperties authProperties;

    @Autowired
    CommUserService commUserService;

    @Override
    public LoginResponse login(LoginRequest request) {
        LoginRequest<Oauth2User> loginRequest = (LoginRequest<Oauth2User>) request;
        AuthUser user = thridService.findByUser(request.getLoginType().name(), loginRequest.getData().getUserId());
        if (user == null) {
            //如果自动创建用户，则创建用户
            if (authProperties.getGithub().getAutoCreateUser()) {
                AuthUser newUser = commUserService.CreateUserWithOauth(loginRequest.getData(), request.getLoginType());
                LoginResponse loginResponse = new LoginResponse();
                loginResponse.setUserId(newUser.getUserId());
                loginResponse.setUserName(newUser.getUserName());
                return loginResponse;
            } else {
                //如果没有，则跳转到绑定用户界面,由调用方确定跳到哪个页面
                LoginResponse loginResponse = new LoginResponse();
                loginResponse.setIsRedirectBind(true);
                loginResponse.setBingData(loginRequest.getData());
                return loginResponse;
            }
        } else {
            //找到用户，直接返回用户信息
            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setUserId(user.getUserId());
            loginResponse.setUserName(user.getUserName());
            return loginResponse;
        }
    }

}
